﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LDCRNewEdit.UI.地图编辑.场景地图设计;
using LDCRNewEdit.Utils;
using System.IO;
using LDCRNewEdit.Services;
using LDCRNewEdit.Model;
using LDCRNewEdit.UI.游戏数据;

namespace LDCRNewEdit
{
    public partial class MainForm : Form
    {

        private SceneGroundForm sceneGroundForm;
        private SceneMapEdit SceneMapEdit;
        private BaseDataForm BaseDataForm;
        private SceneEventForm SceneEventForm;

        public MainForm()
        {
            InitializeComponent();
        }

        private void FormClosingEvent(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            ((Form)sender).Hide();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("是否确定要退出程序？", "提示", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
            {
                this.Dispose();
                Application.Exit();
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void 地面设计ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (sceneGroundForm == null)
            {
                sceneGroundForm = new SceneGroundForm();

                sceneGroundForm.MdiParent = this;
                sceneGroundForm.FormClosing += FormClosingEvent;
            }

            sceneGroundForm.WindowState = FormWindowState.Maximized;
            sceneGroundForm.Show();
            sceneGroundForm.Activate();

        }

        

        private void 建筑设计ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (SceneMapEdit == null)
            {
                SceneMapEdit = new SceneMapEdit();

                SceneMapEdit.MdiParent = this;
                SceneMapEdit.FormClosing += FormClosingEvent;
            }

            SceneMapEdit.WindowState = FormWindowState.Maximized;
            SceneMapEdit.Show();
            SceneMapEdit.Activate();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {

            string filepath = "GamePath.txt";
            if (!SetGamePath(filepath))
            {
                this.Dispose();
                Application.Exit();
                return;
            }


            
            try
            {
                Resources.LoadXML("filePathManager.xml");
                BaseDataService.InitBaseDataFormat();

                //初始化字符集转换
                CharSetUtil.Init();


                //加载基础数据
                foreach (string key in BaseDataService.BaseDataFormatList.Keys)
                {
                    BaseDataService.BaseDataList[key] = LoadData(BaseDataService.BaseDataPathList[key].DatFilename, BaseDataService.BaseDataFormatList[key]);
                }

            }
            catch (FileNotFoundException ex)
            {
                MessageBox.Show("找不到游戏资源，编辑器将要退出!"+ex.Message);
                if (File.Exists(filepath)) File.Delete(filepath);
                this.Dispose();
                Application.Exit();
                return;
            }

            //Action
            string actionfilename = Resources.GamePath + "data/action/action.dat";
            using (FileStream fs = new FileStream(actionfilename, FileMode.Create))
            {
                List<byte[]> list = new List<byte[]>();

                list.Add(Tools.ShortToBytes((short)1));     //总数

                list.Add(new byte[] { (byte)3 });     //贴图个数
                list.Add(Tools.ShortToBytes((short)0));     //数值
                list.Add(new byte[] { (byte)'D' });     //默认
                list.Add(new byte[] { (byte)4 });     //每格多少帧
                list.Add(Tools.ShortToBytes((short)1));     //数值
                list.Add(new byte[] { (byte)'W' });     //默认
                list.Add(new byte[] { (byte)2 });     //每格多少帧
                list.Add(Tools.ShortToBytes((short)2));     //数值
                list.Add(new byte[] { (byte)'F' });     //默认
                list.Add(new byte[] { (byte)2 });     //每格多少帧
                /*
                list.Add(new byte[] { (byte)2 });     //贴图个数
                list.Add(Tools.ShortToBytes((short)3));     //数值
                list.Add(new byte[] { (byte)'D' });     //默认
                list.Add(new byte[] { (byte)4 });     //每格多少帧
                list.Add(Tools.ShortToBytes((short)4));     //数值
                list.Add(new byte[] { (byte)'W' });     //默认
                list.Add(new byte[] { (byte)4 });     //每格多少帧
                */
                foreach (byte[] bytes in list)
                {
                    fs.Write(bytes, 0, bytes.Length);
                }
            }
        }


        /// <summary>
        /// 设置游戏目录
        /// </summary>
        private bool SetGamePath(string filepath)
        {
            //获取游戏目录
            bool flag = false;
            if (File.Exists(filepath))
            {
                using (StreamReader sr = new StreamReader(filepath))
                {
                    string gamepath = sr.ReadLine().Trim();
                    if (Directory.Exists(gamepath))
                    {
                        Resources.GamePath = gamepath.Replace("/", "\\");
                        flag = true;
                    }
                }
            }

            //选择游戏目录
            if (!flag)
            {
                FolderBrowserDialog ofd = new FolderBrowserDialog();
                ofd.Description = "先选择游戏目录";
                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Resources.GamePath = ofd.SelectedPath;



                    //保存路径
                    using (StreamWriter sw = new StreamWriter(filepath))
                    {
                        sw.WriteLine(Resources.GamePath);
                    }

                    flag = true;
                }
            }

            return flag;
        }


        private List<BaseData> LoadData(string datFile, List<BaseDataFormat> formatList)
        {
            //打开数据
            try
            {
                using (FileStream fs = new FileStream(datFile, FileMode.Open))
                {
                    byte[] buf = new byte[fs.Length];
                    fs.Read(buf, 0, buf.Length);
                    fs.Close();

                    int size = 0;      //一个人物数据的长度
                    int num = 0;       //人物数量

                    foreach (BaseDataFormat df in formatList)
                    {
                        size += df.ArrayNum * df.GroupNum * df.Len;
                    }

                    num = buf.Length / size;      //人物个数
                    if (buf.Length % size != 0)
                    {
                        num++;
                    }

                    List<BaseData> baseDataList = new List<BaseData>();
                    int offset = 0;
                    for (int n = 0; n < num; n++)
                    {
                        BaseData baseData = new BaseData();

                        List<BaseDataValue> list = new List<BaseDataValue>();

                        for (int i = 0; i < formatList.Count; )
                        {
                            BaseDataFormat df = formatList[i];
                            for (int j = 0; j < df.ArrayNum; j++)
                            {
                                BaseDataValue data = new BaseDataValue(df);

                                if (buf.Length < df.Len + offset)
                                {
                                    data.Value = "-1";
                                }
                                else
                                {
                                    data.Value = Tools.BytesToString(buf, df.Len, df.IsString == 1, offset);
                                }
                                if (df.ArrayNum > 1)
                                {
                                    data.Text = data.Text + (j + 1);
                                }

                                list.Add(data);

                                offset += data.Len;

                                //如果有数组，则直接读取数组
                                for (int k = 1; k < df.GroupNum; k++)
                                {
                                    data = new BaseDataValue(formatList[i + k]);
                                    if (buf.Length < df.Len + offset)
                                    {
                                        data.Value = "-1";
                                    }
                                    else
                                    {
                                        data.Value = Tools.BytesToString(buf, df.Len, df.IsString == 1, offset);
                                    }

                                    if (df.ArrayNum > 1)
                                    {
                                        data.Text = data.Text + (j + 1);
                                    }

                                    list.Add(data);

                                    offset += data.Len;
                                }

                                if (data.IsName == 1)
                                {
                                    baseData.Name = data.Value;
                                }

                            }
                            i += df.GroupNum;
                        }

                        baseData.DataList = list;

                        baseDataList.Add(baseData);
                    }

                    return baseDataList;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return new List<BaseData>();
            }
        }

        private void 基础数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (BaseDataForm == null)
            {
                BaseDataForm = new BaseDataForm();

                BaseDataForm.MdiParent = this;
                BaseDataForm.FormClosing += FormClosingEvent;
            }

            BaseDataForm.WindowState = FormWindowState.Maximized;
            BaseDataForm.Show();
            BaseDataForm.Activate();
            
        }

        private void 事件数据设计ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (SceneEventForm == null)
            {
                SceneEventForm = new SceneEventForm();

                SceneEventForm.MdiParent = this;
                SceneEventForm.FormClosing += FormClosingEvent;
            }

            SceneEventForm.WindowState = FormWindowState.Maximized;
            SceneEventForm.Show();
            SceneEventForm.Activate();
        }
    }
}
